package com.zanfeng.signleplatform.config.advices;

import com.zanfeng.signleplatform.api.exception.UnAuthorizedException;
import com.zanfeng.signleplatform.auth.WtAuthorization;
import com.zanfeng.signleplatform.common.auth.ApiTokenResult;
import com.zanfeng.signleplatform.config.utils.ApplicationContextUtil;
import com.zanfeng.signleplatform.constants.Constants;
import com.zanfeng.signleplatform.modules.token.TokenHelper;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class BaseAuthorizationInterceptor {

    private void handlePreHandle(String tokenPrefix, HttpServletRequest request, HttpServletResponse response, Object handler) {
        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //从header中得到token
        String xAccessToken = request.getHeader(Constants.kAuth_xAccessToken);
        WtAuthorization wtAuthorization = method.getAnnotation(WtAuthorization.class);
        if (wtAuthorization != null) {
            TokenHelper tokenHelper = ApplicationContextUtil.getBean(TokenHelper.class);
            ApiTokenResult apiTokenResult = tokenHelper.checkToken(tokenPrefix, xAccessToken);
            if (apiTokenResult == null)
                throw new UnAuthorizedException();
            request.setAttribute(Constants.kAuth_tokenResult, apiTokenResult);
        }
    }

    protected void handleApiPreHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        this.handlePreHandle(Constants.kPrefix_API, request, response, handler);
    }

    protected void handleModulePreHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        this.handlePreHandle(Constants.kPrefix_Module, request, response, handler);
    }
}
